package com.yskj.mwk.service.impl;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.qcloud.cos.COSClient;
import com.yskj.mwk.bean.*;
import com.yskj.mwk.dao.ManagerMapper;
import com.yskj.mwk.dao.UserMapper;
import com.yskj.mwk.service.ManagerService;
import com.yskj.mwk.utils.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class ManagerServiceImpl implements ManagerService {
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private COSClient cosClient;

    @Value("${tencent.cos.bucketName}")
    private String bucketName;

    private final JiTuUtil jiTuUtil;
    private final WxUtils wxUtils;
    private final QRCodeGenerator qrCodeGenerator;
    private final PdfCover pdfCover;

    @Autowired
    public ManagerServiceImpl(JiTuUtil jiTuUtil,WxUtils wxUtils,QRCodeGenerator qrCodeGenerator,PdfCover pdfCover) {
        this.jiTuUtil = jiTuUtil;
        this.wxUtils = wxUtils;
        this.qrCodeGenerator = qrCodeGenerator;
        this.pdfCover = pdfCover;
    }

    /**
     * 登录管理后台
     * */
    @Override
    public Supplier loginManager(int type, String tell, String pwd) {

        return managerMapper.loginMa(tell,pwd,type);
    }

    /**
     * 头部四方格数据
     * unit 1￥ 2% 3无
     * type 1增加 2减少 3不变
     * */
    @Override
    public List<Map<String, Object>> getIndexTopData(int accountType, int accountId) {
        List<Map<String, Object>> list = new ArrayList<>();
        String nowMonth= DateUtil.format(DateUtil.date(), "yyyy-MM");//当前月份
        String lastMonth= DateUtil.format(DateUtil.lastMonth(), "yyyy-MM");//上个月份

        BigDecimal nowSalesVolume=null;//本月销售额
        BigDecimal lastSalesVolume=null;//上月销售额
        int nowOrderNum=0;
        int lastOrderNum=0;
        if (accountType == 1) {
            nowSalesVolume=managerMapper.sumTotalPriceBySupplierId(accountId,nowMonth);
            lastSalesVolume=managerMapper.sumTotalPriceBySupplierId(accountId,lastMonth);
            nowOrderNum= managerMapper.sumTotalOrderNumBySupplierId(accountId,nowMonth);
            lastOrderNum= managerMapper.sumTotalOrderNumBySupplierId(accountId,lastMonth);
        }else{
            nowSalesVolume=managerMapper.sumTotalPrice(nowMonth);
            lastSalesVolume=managerMapper.sumTotalPrice(lastMonth);
            nowOrderNum= managerMapper.sumTotalOrderNum(nowMonth);
            lastOrderNum= managerMapper.sumTotalOrderNum(lastMonth);
        }
        if (nowSalesVolume == null) {
            nowSalesVolume = BigDecimal.ZERO;
        }
        if (lastSalesVolume == null) {
            lastSalesVolume = BigDecimal.ZERO;
        }
        //计算差值
        int type1=1;
        String infos1="";
        BigDecimal result1 = nowSalesVolume.subtract(lastSalesVolume);
        BigDecimal percentage1=BigDecimal.ZERO;
        if(lastSalesVolume.compareTo(BigDecimal.ZERO) != 0) {
            percentage1 = result1
                    .divide(lastSalesVolume, 4, RoundingMode.HALF_UP) // 除以上个月的收入，结果保留4位小数，四舍五入
                    .multiply(BigDecimal.valueOf(100));
        }else{
            percentage1= BigDecimal.valueOf(100);
        }
        if (result1.compareTo(BigDecimal.ZERO) > 0) {
            infos1="较上月增长"+percentage1;
        } else if (result1.compareTo(BigDecimal.ZERO) < 0) {
            type1=2;
            infos1="较上月减少"+percentage1;
        } else {
            type1=3;
            infos1="较上月持平";
        }

        //订单量
        int type2 =1;
        String infos2="";
        int result2 = nowOrderNum - lastOrderNum;
        BigDecimal result2BigDecimal = new BigDecimal(result2);
        BigDecimal lastOrderNumBigDecimal = new BigDecimal(lastOrderNum);

        BigDecimal percentage2 =BigDecimal.ZERO;
        if(lastOrderNumBigDecimal.compareTo(BigDecimal.ZERO) != 0) {
            percentage2 = result2BigDecimal
                    .divide(lastOrderNumBigDecimal, 4, RoundingMode.HALF_UP) // 除以上个月的订单量，结果保留4位有效数字，四舍五入
                    .multiply(BigDecimal.valueOf(100)) // 乘以100转换成百分比
                    .setScale(2, RoundingMode.HALF_UP);
        }else{
            percentage2= BigDecimal.valueOf(100);
        }
        if (result2 > 0) {
            infos2="较上月增长"+percentage2;
        } else if (result2<0) {
            type2 =2;
            infos2="较上月减少"+percentage2;
        }else {
            type2 =3;
            infos2="较上月持平";
        }

        //计算平均单价
        BigDecimal nowAverageUnitPrice = BigDecimal.ZERO;
        BigDecimal lastAverageUnitPrice = BigDecimal.ZERO;
        if (nowOrderNum!=0){
            nowAverageUnitPrice = nowSalesVolume.divide(new BigDecimal(nowOrderNum), 2, RoundingMode.HALF_UP);
        }
        if(lastOrderNum!=0){
            lastAverageUnitPrice = lastSalesVolume.divide(new BigDecimal(lastOrderNum), 2, RoundingMode.HALF_UP);
        }
        int type3=1;
        String infos3="";
        BigDecimal result3 = nowAverageUnitPrice.subtract(lastAverageUnitPrice);
        BigDecimal percentage3 =BigDecimal.ZERO;
        if(lastAverageUnitPrice.compareTo(BigDecimal.ZERO) != 0) {
            percentage3 = result3
                    .divide(lastAverageUnitPrice, 4, RoundingMode.HALF_UP) // 除以上个月的收入，结果保留4位小数，四舍五入
                    .multiply(BigDecimal.valueOf(100));
        }else{
            percentage3= BigDecimal.valueOf(100);
        }
        if (result3.compareTo(BigDecimal.ZERO) > 0) {
            infos3="较上月增长"+percentage3;
        } else if (result3.compareTo(BigDecimal.ZERO) < 0) {
            type3=2;
            infos3="较上月减少"+percentage3;
        } else {
            type3=3;
            infos3="较上月持平";
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("title", "销售额");
        map1.put("content", nowSalesVolume);
        map1.put("unit", 1);
        map1.put("type", type1);
        map1.put("infos",infos1);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("title", "订单数");
        map2.put("content", nowOrderNum);
        map2.put("unit", 3);
        map2.put("type",type2);
        map2.put("infos",infos2);

        Map<String, Object> map3 = new HashMap<>();
        map3.put("title", "平均订单金额");
        map3.put("content", nowAverageUnitPrice);
        map3.put("unit", 1);
        map3.put("type",type3);
        map3.put("infos",infos3);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        if (accountType==0){
            int nowCustomerNum= managerMapper.sumNewCustomerNum(nowMonth);
            int lastCustomerNum= managerMapper.sumNewCustomerNum(lastMonth);

            int type4 =1;
            String infos4="";
            int result4 = nowCustomerNum - lastCustomerNum;
            BigDecimal result4BigDecimal = new BigDecimal(result4);
            BigDecimal lastCustomerNumBigDecimal = new BigDecimal(lastCustomerNum);
            BigDecimal percentage4;
            if (lastCustomerNumBigDecimal.compareTo(BigDecimal.ZERO) != 0) {
                percentage4 = result4BigDecimal
                        .divide(lastCustomerNumBigDecimal, 4, RoundingMode.HALF_UP) // 除以上个月的订单量，结果保留4位有效数字，四舍五入
                        .multiply(BigDecimal.valueOf(100)) // 乘以100转换成百分比
                        .setScale(2, RoundingMode.HALF_UP);
            }else{
                percentage4= BigDecimal.valueOf(100);;
            }
            if (result4 > 0) {
                infos4="较上月增长"+percentage4;
            } else if (result4<0) {
                type4 =2;
                infos4="较上月减少"+percentage4;
            }else {
                type4 =3;
                infos4="较上月持平";
            }

            Map<String, Object> map4 = new HashMap<>();
            map4.put("title", "新增客户");
            map4.put("content", nowCustomerNum);
            map4.put("unit", 3);
            map4.put("type",type4);
            map4.put("infos",infos4);
            list.add(map4);
        }else{
            BigDecimal nowChengben=managerMapper.sumTotalChengben(nowMonth);
            BigDecimal lastChengben=managerMapper.sumTotalChengben(lastMonth);
            if (nowChengben==null){
                nowChengben=BigDecimal.ZERO;
            }
            if (lastChengben==null){
                lastChengben=BigDecimal.ZERO;
            }
            BigDecimal nowProfit=nowChengben.subtract(nowSalesVolume);
            BigDecimal lastProfit=lastChengben.subtract(lastSalesVolume);

            int type5=1;
            String infos5="";
            BigDecimal result5 = nowProfit.subtract(lastProfit);
            BigDecimal percentage5;
            if (lastProfit.compareTo(BigDecimal.ZERO) != 0) {
                percentage5 = result5
                        .divide(lastProfit, 4, RoundingMode.HALF_UP) // 除以上个月的收入，结果保留4位小数，四舍五入
                        .multiply(BigDecimal.valueOf(100));
            }else{
                percentage5= BigDecimal.valueOf(100);;
            }
            if (result5.compareTo(BigDecimal.ZERO) > 0) {
                infos5="较上月增长"+percentage5;
            } else if (result5.compareTo(BigDecimal.ZERO) < 0) {
                type5=2;
                infos5="较上月减少"+percentage5;
            } else {
                type5=3;
                infos5="较上月持平";
            }

            Map<String, Object> map5 = new HashMap<>();
            map5.put("title", "利润");
            map5.put("content", nowProfit);
            map5.put("unit", 1);
            map5.put("type",type5);
            map5.put("infos",infos5);
            list.add(map5);
        }
        return list;
    }

    /**
     * 获取一年12月 每月的销售额和订单量
     * */
    @Override
    public Map<String, Object> getIndexLeftData(int accountType, int accountId) {
        String nowYear= DateUtil.format(DateUtil.date(), "yyyy");
        List<Integer> oNums = new ArrayList<>();
        List<String> oMoneys = new ArrayList<>();
        for(int i=1;i<=12;i++){
            String month=i+"";
            if (i<10){
                month="0"+month;
            }
            String nowMonth=nowYear+"-"+month;
            //获取每月的销售额和订单量
            if (accountType==0){
                BigDecimal money=managerMapper.sumTotalPrice(nowMonth);
                int num=managerMapper.sumTotalOrderNum(nowMonth);
                oNums.add(num);
                if (money==null){
                    money=BigDecimal.ZERO;
                }
                oMoneys.add(money.toString());
            }else{
                BigDecimal money=managerMapper.sumTotalPriceBySupplierId(accountId,nowMonth);
                int num=managerMapper.sumTotalOrderNumBySupplierId(accountId,nowMonth);
                oNums.add(num);
                if (money==null){
                    money=BigDecimal.ZERO;
                }
                oMoneys.add(money.toString());
            }
        }
        Map<String, Object> map=new HashMap<>();
        map.put("oNums", oNums);
        map.put("oMoneys", oMoneys);
        return map;
    }

    /**
     * 获取当月主要三种订单状态
     * 待发货
     * 待收货
     * 售后中
     * */
    @Override
    public Map<String, Integer> getIndexRightData(int accountType, int accountId) {
        String nowMonth= DateUtil.format(DateUtil.date(), "yyyy-MM");//当前月份
        Map<String, Integer> map=new HashMap<>();
        int num1=0;
        int num2=0;
        int num3=0;
        if (accountType==0){
            num1=managerMapper.totalOrdersNumByOrderStatus(2,nowMonth);
            num2=managerMapper.totalOrdersNumByOrderStatus(3,nowMonth);
            num3=managerMapper.totalOrdersNumByOrderStatus(5,nowMonth);
        }else{
            num1=managerMapper.totalOrdersNumByOrderStatusAndSupplierId(accountId,2,nowMonth);
            num2=managerMapper.totalOrdersNumByOrderStatusAndSupplierId(accountId,3,nowMonth);
            num3=managerMapper.totalOrdersNumByOrderStatusAndSupplierId(accountId,5,nowMonth);
        }
        map.put("num1", num1);
        map.put("num2", num2);
        map.put("num3", num3);
        return map;
    }

    /**
     * 获取销量最高的前10个商品
     * */
    @Override
    public Map<String, Object> getIndexBottomData(int accountType, int accountId ,String searchMonth) {
        List<Integer> salesNums = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        List<Map<String, Object>> list = null;
        if (accountType==0){
            list=managerMapper.getHighSellingProducts(searchMonth);
        }else{
            list=managerMapper.getHighSellingProductsBySupplierId(accountId,searchMonth);
        }
        for (Map<String, Object> map : list) {
            // 内层循环：遍历Map中的每个键值对
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();       // 获取键
                Object value = entry.getValue();   // 获取值
                if (key.equals("count")) {
                    int count=Integer.parseInt(value.toString());
                    salesNums.add(count);
                }
                if (key.equals("goodsName")) {
                    String name=value.toString();
                    nameList.add(name);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("salesNums", salesNums);
        map.put("nameList", nameList);
        return map;
    }

    /**
     * 获取租户列表
     * 可以根据名称筛选
     * */
    @Override
    public PageInfo<Supplier> getSuppliersByPage(String name, int pageNum, int pageSize) {
        Page<Supplier> supplierPage =managerMapper.getSuppliersByPage(name,pageNum, pageSize);
        return new PageInfo<>(supplierPage);
    }

    /**
     * 新增租户
     * */
    @Override
    public int addSupplier(int supplierId,String supplierName, String supplierPhone, String supplierPwd, int supplierType,String supplierAddress,String supplierLxr) {
        Supplier supplier=new Supplier();
        supplier.setSupplierId(supplierId);
        supplier.setSupplierName(supplierName);
        supplier.setSupplierPhone(supplierPhone);
        supplier.setSupplierPwd(supplierPwd);
        supplier.setSupplierType(supplierType);
        supplier.setCreateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
        supplier.setSupplierAddress(supplierAddress);
        supplier.setSupplierLxr(supplierLxr);
        if (supplierId==0){
            return managerMapper.addSupplier(supplier);
        }else{
            return managerMapper.updateSupplier(supplier);
        }
    }

    /**
     * 获取租户详情
     * */
    @Override
    public Supplier getSupplierDescById(int id) {
        return managerMapper.getSupplierDescById(id);
    }


    /**
     * 获取客户列表
     * */
    @Override
    public PageInfo<User> getUsersByPage(String name, String tell, int pageNum, int pageSize) {
        Page<User> userPage =managerMapper.getUsersByPage(name,tell,pageNum, pageSize);
        return new PageInfo<>(userPage);
    }


    /**
     * 获取订单列表
     * */
    @Override
    public PageInfo<Order> getOrdersByPage(int pageNum, int pageSize, int accountType, int accountId, String orderId, int orderStatus,String orderTime1,String orderTime2,String getPdfTime1,String getPdfTime2,String downloadTime1,String downloadTime2,String isDownload,String trackingNo) {
        Page<Order> orderPage =null;
        int isDownload_int=-1;
        if (!"".equals(isDownload)){
            isDownload_int=Integer.parseInt(isDownload);
        }
        if (accountType==0){
            orderPage=managerMapper.getOrdersByPage(orderId,pageNum,pageSize,orderTime1,orderTime2,getPdfTime1,getPdfTime2,downloadTime1,downloadTime2,trackingNo,orderStatus,isDownload_int);

        }else{
            orderPage=managerMapper.getOrdersByPageAndSupplierId(orderId,pageNum,pageSize,orderTime1,orderTime2,getPdfTime1,getPdfTime2,downloadTime1,downloadTime2,trackingNo,orderStatus,isDownload_int,accountId);
        }
        return new PageInfo<>(orderPage);
    }

    /**
     * 获取订单内商品详情
     * */
    @Override
    public List<OrderDesc> getOrdersDescList(String orderId) {
        return managerMapper.getOrdersDescList(orderId);
    }

    /**
     * 获取分类列表
     * parentId=0 一级
     * */
    @Override
    public PageInfo<Sort> getSortByPage(int pageNum, int pageSize, int parentId) {
        Page<Sort> sortPage =managerMapper.getSortByPage(pageNum, pageSize, parentId);
        return new PageInfo<>(sortPage);
    }

    /**
     * 删除分类
     * */
    @Override
    public int deleteSortById(int id) {
        return managerMapper.deleteSortById(id);
    }

    /**
     * 修改分类是否显示
     * */
    @Override
    public int updateSortStatusById(int id, int isShow) {
        if (isShow==0){
            isShow=1;
        }else{
            isShow=0;
        }
        return managerMapper.updateSortIsshowById(id,isShow);
    }

    /**
     * 新增或修改分类
     * */
    @Override
    public int addSort(String iconPic, String name, int isShow, int level, int parentId, int type, int id) {
        int res=0;
        Sort sort=new Sort();
        sort.setIconPic(iconPic);
        sort.setName(name);
        sort.setIsShow(isShow);
        sort.setLevel(level);
        sort.setParentId(parentId);
        sort.setType(type);
        sort.setId(id);
        if (id==0){
            //新增
            res=managerMapper.addSort(sort);
        }else{
            res=managerMapper.updateSortById(sort);
        }
        return res;
    }

    /**
     * 获取分类详情
     * */
    @Override
    public Sort getSortDescById(int id) {
        return managerMapper.getSortDescById(id);
    }

    /**
     * 获取商品的利润
     * 筛选日期
     * */
    @Override
    public PageInfo<GoodsSpuSale> getGoodsSpuSalePageByTime(String startTime, String endTime, String spuName, int pageNum, int pageSize) {
        Page<GoodsSpuSale> goodsPage =null;
        if (startTime.isEmpty()&&endTime.isEmpty()){
            goodsPage=managerMapper.getGoodsSpuSalePage(spuName,pageNum,pageSize);
        }else{
            goodsPage=managerMapper.getGoodsSpuSalePageByTime(startTime,endTime,spuName,pageNum,pageSize);
        }
        return new PageInfo<>(goodsPage);
    }


    /**
     * 获取产品列表
     * */
    @Override
    public PageInfo<Goods> getGoodsPage(String spuName, int sort2Id, int publishStatus, int supplierId, int isDiy, int isPopular, int isNew, int level, int pageNum, int pageSize,int isJingxuan,int isMiaosha) {
        Page<Goods> goodsPage =managerMapper.getGoodsPage(spuName,sort2Id,publishStatus,supplierId,isDiy,isPopular,isNew,level,pageNum,pageSize, isJingxuan, isMiaosha);
        return new PageInfo<>(goodsPage);
    }

    /**
     * 获取租户列表不分页
     * */
    @Override
    public List<Supplier> getAllSuppliers(String supplierName) {
        return managerMapper.getAllSuppliers(supplierName);
    }

    /**
     * 获取所有分类
     * */
    @Override
    public List<Sort> getAllSorts(int parentId) {
        return managerMapper.getAllSorts(parentId);
    }

    /**
     * 获取商品主表详情
     * */
    @Override
    public Goods getGoodsById(int id) {
        return managerMapper.getGoodsSpu(id);
    }

    /**
     * 编辑或新增商品主表
     * */
    @Override
    public int addGoods(int spuId, String spuName, String spuDesc, int sort1Id, int sort2Id, int supplierId, int publishStatus, int isNew, int isPopular, int isDiy, int level, int minNum,double price,int sourceId,int isJingxuan,int isMiaosha,int isMatting,int isTwo) {
        Goods goods=new Goods();
        goods.setSpuId(spuId);
        goods.setSpuName(spuName);
        goods.setSpuDesc(spuDesc);
        goods.setSort1Id(sort1Id);
        goods.setSort2Id(sort2Id);
        goods.setSupplierId(supplierId);
        Supplier supplier=managerMapper.getSupplierDescById(supplierId);
        goods.setSupplierName(supplier.getSupplierName());
        goods.setPublishStatus(publishStatus);
        goods.setIsNew(isNew);
        goods.setIsPopular(isPopular);
        goods.setIsDiy(isDiy);
        goods.setLevel(level);
        goods.setMinNum(minNum);
        goods.setIsPromotion(0);
        goods.setPrice(BigDecimal.valueOf(price));
        goods.setCreateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
        goods.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
        goods.setSourceId(sourceId);
        goods.setIsJingxuan(isJingxuan);
        goods.setIsMiaosha(isMiaosha);
        goods.setIsMatting(isMatting);
        goods.setIsTwo(isTwo);
        int res=0;
        if(spuId==0){
            res=managerMapper.addGoodsSpu(goods);
        }else{
            res=managerMapper.editGoodsSpu(goods);
        }
        return res;
    }


    /**
     * 获取商品全部图片
     * */
    @Override
    public List<GoodsImage> getGoodsImageList(int id, int type) {
        return managerMapper.getGoodsImage(type,id);
    }

    /**
     * 添加图片
     * */
    @Override
    public int addGoodsImage(int id, int type, int level, int spuId, String picUrl) {
        String[] picUrls = picUrl.split(";");
        int res=1;
        for (String pic : picUrls) {
            if (id==0){
                //新增
                res=managerMapper.addGoodsImage(pic,type,level,spuId);
            }else{
                res=managerMapper.editGoodsImage(pic,level,id);
            }
        }
        if(type==1){
            //获取最新主图跟新到goods_spu表
            String mainPic=managerMapper.getGoodsMainPic(spuId);
            res=managerMapper.editGoodsMainPic(spuId,mainPic);
        }
        return res;
    }

    @Override
    public int delGoodsImage(int id) {
        return managerMapper.deleteGoodsImage(id);
    }

    @Override
    public GoodsImage getGoodsImageById(int id) {
        return managerMapper.getGoodsImageById(id);
    }


    /**
     * 获取商品sku列表
     * */
    @Override
    public PageInfo<GoodsSku> getGoodsSkuList(int id, int pageNum, int pageSize) {
        Page<GoodsSku> goodsPage =managerMapper.getGoodsSkuList(id,pageNum,pageSize);
        return new PageInfo<>(goodsPage);
    }

    /**
     * 批量修改sku详细信息
     * */
    @Override
    public int editGoodsSku(String ids, double salesPrice, double underlinedPrice, double costPrice, int enable, String skuPic,int stock) {
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        int res=managerMapper.editStock(idsList,stock);
        int res1=0;
        if (res > 0) {
            res1=managerMapper.editGoodsSku(idsList,salesPrice,underlinedPrice,costPrice,enable,skuPic);
        }
        return res1;
    }

    /**
     * 获取sku详情
     * */
    @Override
    public GoodsSku getGoodsSkuDescById(int id) {
        return managerMapper.getGoodsSkuById(id);
    }

    @Override
    public Map<String, Object> getGoodsSpecById(int id) {
        String spec=managerMapper.getGoodsSpecById(id);
        //获取sku属性信息 json格式字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (spec!=null) {
                return objectMapper.readValue(spec, LinkedHashMap.class);
            }else{
                return null;
            }
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int updateGoodsSpec(int id, String spec) {
        String sql_spec =managerMapper.getGoodsSpecById(id);
        if (sql_spec !=null) {
            managerMapper.updateGoodsSpec(id,spec);
        }else{
            managerMapper.addGoodsSpec(id,spec);
        }
        Goods goods=managerMapper.getGoodsSpu(id);
        int sort1Id=goods.getSort1Id();
        int sort2Id=goods.getSort2Id();
        managerMapper.deleteGoodsSkuStock(id);
        managerMapper.deleteGoodsSku(id);
        GenerateGoodsSkuUtil generateGoodsSkuUtil=new GenerateGoodsSkuUtil();
        List<GoodsSpec> goodsSpecList=generateGoodsSkuUtil.generate(spec);
        String createTime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        for (GoodsSpec goodsSpec:goodsSpecList) {
            System.out.println(goodsSpec);
            String own_spec=goodsSpec.getOwn_spec();
            String indexes=goodsSpec.getIndexes();

            AddSkuBean addSkuBean=new AddSkuBean();
            addSkuBean.setSpuId(id);
            addSkuBean.setSort1Id(sort1Id);
            addSkuBean.setSort2Id(sort2Id);
            addSkuBean.setIndexes(indexes);
            addSkuBean.setOwn_spec(own_spec);
            addSkuBean.setCreateTime(createTime);
            System.out.println(addSkuBean);

            userMapper.addSkuSpec(addSkuBean);
            userMapper.addSkuStock(addSkuBean.getSkuId());
        }
        return 0;
    }

    @Override
    public int editSupplierWuliuConfig(int supplierId, String jt_apiAccount, String jt_privateKey, String jt_customerCode, String jt_orderPassword, String sendAddress, String sendName, String sendTell, String sendProv, String sendCity, String sendArea) {
        String sid=managerMapper.checkSupplierIsAdd(supplierId);
        Logistics logistics=new Logistics();
        logistics.setJt_apiAccount(jt_apiAccount);
        logistics.setJt_privateKey(jt_privateKey);
        logistics.setJt_customerCode(jt_customerCode);
        logistics.setJt_orderPassword(jt_orderPassword);
        logistics.setSupplierId(supplierId);
        logistics.setSendAddress(sendAddress);
        logistics.setSendName(sendName);
        logistics.setSendTell(sendTell);
        logistics.setSendProv(sendProv);
        logistics.setSendCity(sendCity);
        logistics.setSendArea(sendArea);
        int res=0;
        if (sid==null) {
            res=managerMapper.addLogisticsConfig(logistics);
        }else{
            res=managerMapper.updateLogisticsConfig(logistics);
        }
        return res;
    }

    @Override
    public Logistics getSupplierWuliuConfig(int supplierId) {
        return managerMapper.getLogisticsById(supplierId);
    }


    /**
     * 获取模板边框分类
     * */
    @Override
    public PageInfo<TemplateSort> getTemplateImageByPage(int pageNum, int pageSize,int parentId,int type) {
        Page<TemplateSort> templateSorts =managerMapper.getTemplateImageSortList(pageNum,pageSize,parentId,type);
        return new PageInfo<>(templateSorts);
    }

    @Override
    public int editTemplateImageByPage(String sortName, int isShow, int level, int id,int parentId,int type) {
        int res=0;
        if (id==0){
            res=managerMapper.addTemplateImageSort(sortName,isShow,level,parentId,type);
        }else{
            res=managerMapper.updateTemplateImageSort(sortName,isShow,level,id);
        }
        return res;
    }

    /**
     * 删除
     * */
    @Override
    public int delTemplateImageByPage(int id) {
        return managerMapper.delTemplateImageSort(id);
    }

    /**
     * 修改是否显示
     * */
    @Override
    public int updateTemplateImageSortStatus(int isShow, int id) {
        return managerMapper.updateTemplateImageSortStatus(isShow,id);
    }

    @Override
    public PageInfo<TemplatePackage> getTemplatePackageByPage(int pageNum, int pageSize) {
        Page<TemplatePackage> templatePackages =managerMapper.getTemplatePackageByPage(pageNum,pageSize);
        return new PageInfo<>(templatePackages);
    }

    @Override
    public int editTemplatePackageByPage(String name, int id) {
        int res=0;
        if (id==0){
            res=managerMapper.addTemplatePackage(name);
        }else{
            res=managerMapper.updateTemplatePackage(name,id);
        }
        return res;
    }

    @Override
    public int delTemplatePackage(int id) {
        return managerMapper.delTemplatePackage(id);
    }

    @Override
    public PageInfo<TemplateImage> getTempImageByPage(int pageNum, int pageSize, int sortId,int type) {
        Page<TemplateImage> templateImage =managerMapper.getTempImageByPage(pageNum,pageSize,sortId,type);
        return new PageInfo<>(templateImage);
    }

    @Override
    public int editTempImage(String templatePic, int sortId, int level, int id,int type) {
        int res=0;
        if (id==0){
            res=managerMapper.addTempImage(templatePic,sortId,level,type);
        }else{
            res=managerMapper.editTempImage(templatePic,level,id);
        }
        return res;
    }

    @Override
    public int delTempImage(int id) {
        return managerMapper.delTempImage(id);
    }

    @Override
    public TemplateImage getTempImageDesc(int id) {
        return managerMapper.getTempImageDesc(id);
    }

    @Override
    public List<TemplatePackage> getTemplatePackages() {
        return managerMapper.getTemplatePackages();
    }


    /**
     * 生成pdf
     * */
    @Override
    public String downloadPdf(String url,String orderId) {
        List<String> result = new ArrayList<>();
        List<EditImage> list=managerMapper.getEditImageById(orderId);
        for (EditImage editImage : list) {
            String zpic=editImage.getZpic();
            String fpic=editImage.getFpic();


            String[] zpicArray = zpic.split(";");
            String[] fpicArray = fpic.split(";");

            // 确保两个数组长度一致
            int length = Math.min(zpicArray.length, fpicArray.length);

            for (int i = 0; i < length; i++) {
                result.add(zpicArray[i]);
                result.add(fpicArray[i]);
            }
        }
        Convert2Pdf convert2Pdf=new Convert2Pdf();
        //3.1 判断文件夹是否存在，不存在则创建
        String imageDirPath = "./upload/pdfs/";
        File imageDir = new File(imageDirPath);
        if (!imageDir.exists()){
            imageDir.mkdirs();
        }
        String pdfUrl=imageDirPath+orderId+".pdf";
        convert2Pdf.convert(result,pdfUrl);
        //4.1 正则匹配请求前缀
        Pattern pattern = Pattern.compile("(.*)/manager/.*");
        Matcher matcher = pattern.matcher(url);

        String urlPrefix = "http://localhost:18080";

        while(matcher.find()){
            urlPrefix = matcher.group(1);
        }
        return urlPrefix + "/pdfs/" + orderId+".pdf";
    }


    /**
     * 保存修改首页广告营销图
     * */
    @Override
    public int saveIndexMarketingPoster(String imageUrl) {
        System.out.println(imageUrl);
        return managerMapper.saveIndexMarketingPoster(imageUrl);
    }


    /**
     * 检查订单是否支持退款当前申请的金额
     * //1.退款之前先查看此订单是否支付
     * //2.退款金额是不是小于等于可退款订单金额
     * **/
    @Override
    public int checkOrderIsCanRefund(String orderId,double refundTotal) {
        Order order=managerMapper.getOrderById(orderId);
        if (order==null){
            return 101;
        }else{
            int payStatus=order.getPayStatus();
            if (payStatus==1){
                int oldRefund=managerMapper.getTotalRefundAmontByOrderId(orderId);//已经发起退款金额（分）
                BigDecimal orderTotal=order.getTotalPrice();

                // 将订单总金额转换为分（乘以100后四舍五入取整）
                BigDecimal orderTotalInCents = orderTotal.multiply(BigDecimal.valueOf(100))
                        .setScale(0, RoundingMode.HALF_UP);

                // 计算可退金额（分） = 订单总金额分 - 已退款分
                BigDecimal availableRefund = orderTotalInCents.subtract(BigDecimal.valueOf(oldRefund));

                // 将本次退款金额转换为分（避免double精度问题）
                BigDecimal refundInCents = BigDecimal.valueOf(refundTotal)
                        .multiply(BigDecimal.valueOf(100))
                        .setScale(0, RoundingMode.HALF_UP);

                // 比较可用金额 >= 申请退款金额
                if (availableRefund.compareTo(refundInCents) >= 0) {
                    return 0; // 允许退款
                } else {
                    return 103; // 退款金额超过可退额度
                }
            }else{
                return 102;
            }
        }
    }

    @Override
    public int getFen(String orderId, double refundTotal, int type) {
        if (type==1){
            Order order=managerMapper.getOrderById(orderId);
            BigDecimal orderTotal=order.getTotalPrice();

            // 将订单总金额转换为分（乘以100后四舍五入取整）
            BigDecimal orderTotalInCents = orderTotal.multiply(BigDecimal.valueOf(100))
                    .setScale(0, RoundingMode.HALF_UP);
            return orderTotalInCents.intValueExact();
        }else{
            BigDecimal refundInCents = BigDecimal.valueOf(refundTotal)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(0, RoundingMode.HALF_UP);
            return refundInCents.intValueExact();
        }
    }


    /**
     * 提交退款申请成功 录入表中
     * */
    @Override
    public int saveRefunLogsToSql(OrdersRefund ordersRefund) {
        ordersRefund.setCreateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
        String orderId=ordersRefund.getOrderId();
        int res=managerMapper.updateOrderAfterStatus(orderId,4);
        if (res>=1){
            return managerMapper.saveRefunLogsToSql(ordersRefund);
        }else{
            return 0;
        }
    }

    @Override
    public void updateAfterStatus(String refund_id) {
        int res=managerMapper.updaterefundOrderAfterStatus(refund_id,3,DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
        if (res>=1){
            OrdersRefund ordersRefund=managerMapper.getOrdersRefundDesc(refund_id);
            String orderId=ordersRefund.getOrderId();
            managerMapper.updateOrderAfterStatus(orderId,2);
        }
    }

    @Override
    public int cancelWuliuOrder(int supplierId, String orderId,String wlOrderId) {
        return jiTuUtil.cancelOrder(orderId,supplierId,wlOrderId);
    }

    @Override
    public int addWuliuGuiji(String billCode, String scanTime, String scanType, String desc) {
        int totalnum=managerMapper.getWuliuGuijiNum(billCode,scanTime,scanType);
        if (totalnum==0){
            if (scanType.equals("快件揽收")){
                Order order=managerMapper.getOrderByTrackingNo(billCode);
                //调用小程序发货信息录入接口
                WxShippingUtil wxShippingUtil=new WxShippingUtil();
                String access_token=wxUtils.getAccessToken();
                String transaction_id=order.getTransaction_id();
                //判断此支付订单是否是最后一个发货的订单
                int num=userMapper.getNoFahuoNum(transaction_id);
                String is_all_delivered="";
                if (num>1){
                    is_all_delivered="false";
                }else{
                    is_all_delivered="true";
                }
                String tracking_no=order.getTrackingNo();
                List<OrderDesc> odescList=userMapper.getOrderDescByOrderId(order.getOrderId());
                String orderDesc="";
                if (!odescList.isEmpty()) {
                    orderDesc=odescList.stream()
                            .map(OrderDesc::getGoodsName)    // 提取商品名
                            .filter(goodsName -> goodsName != null && !goodsName.isEmpty()) // 过滤空值
                            .collect(Collectors.joining(", "));
                }
                EnhancedPhoneUtils enhancedPhoneUtils=new EnhancedPhoneUtils();
                String receiverTell=enhancedPhoneUtils.enhancedMask(order.getReceiveTell());
                User user=userMapper.getUserDescByUuid(order.getUuid());
                String openid=user.getOpenid();
                String res=wxShippingUtil.uploadShipping( access_token, transaction_id, is_all_delivered, tracking_no, orderDesc, receiverTell, openid);
            }
            return managerMapper.addWuliuGuiji(billCode,desc,scanTime,scanType);
        }
        return 0;
    }


    /**
     * 批量获取运单号
     * */
    @Override
    public void batchGetTrackingNo(String orderIds) {
        String[] ids = orderIds.split(";");
        // 2. 遍历数组
        for (String orderId : ids) {
            Order order=managerMapper.getOrderById(orderId);
            int isGetTrackingNo=order.getIsGetTrackingNo();
            if(isGetTrackingNo==0){
                OrderNumberGenerator generator = new OrderNumberGenerator();
                String wlOrderId=generator.generateOrderNumber();
                jiTuUtil.addOrder(orderId,order.getSupplierId(),wlOrderId);
            }
        }
    }


    /**
     * 判断有没有生成过面单文件
     * 有直接返回打印
     * 没有调用极兔打印接口
     * */
    @Override
    public String printWaybill(String trackingNo,String url) {
        Order order=managerMapper.getOrderByTrackingNo(trackingNo);
        System.out.println(order);
        int isPrint=order.getIsPrint();
        if (isPrint==0){
            return jiTuUtil.getPrintOrder(order.getOrderId(),trackingNo,order.getSupplierId(),url);
        }else{
            return order.getBase64EncodeContent();
        }
    }

    /**
     * 获取后台订单管理-详情
     * */
    @Override
    public OrderDescMa getOrderDesc(String orderId) {
        Order order=managerMapper.getOrderById(orderId);
        OrderDescMa orderDescMa=new OrderDescMa();
        orderDescMa.setOrderId(orderId);
        orderDescMa.setCreateTime(order.getCreateTime());
        orderDescMa.setLastUpdateTime(order.getLastUpdateTime());
        orderDescMa.setOrderStatus(order.getOrderStatus());
        orderDescMa.setGetPdfTime(order.getGetPdfTime());
        orderDescMa.setPayStatus(order.getPayStatus());
        orderDescMa.setReceiveName(order.getReceiveName());
        orderDescMa.setReceiveTell(order.getReceiveTell());
        orderDescMa.setReceiveAddress(order.getReceiveAddress());
        orderDescMa.setTrackingNo(order.getTrackingNo());
        List<OrderDesc> list=managerMapper.getOrdersDescList(orderId);
        List<OrderInfo> orderInfoList=new ArrayList<>();
        for (OrderDesc orderDesc : list) {
            OrderInfo orderInfo=new OrderInfo();
            String goodsName=orderDesc.getGoodsName();
            String goodsSpec=orderDesc.getGoodsSpec();
            int oid=orderDesc.getOid();
            orderInfo.setOid(oid);
            orderInfo.setGoodsName(goodsName);
            orderInfo.setGoodsDesc(goodsSpec);
            //获取编辑图列表
            List<EditImage> editImages=managerMapper.getEditImageByOid(oid);
            orderInfo.setTiaoshu(editImages.size());
            //获取编辑图总数
            int num=managerMapper.getEditImagesNum(oid);
            orderInfo.setZongshu(num);
            orderInfo.setEditImages(editImages);
            orderInfo.setPdfPages(num*2);
            //获取所以编辑图把他放到一个list中
            List<String> eimageList=new ArrayList<>();
            for(EditImage editImage : editImages){
                String zpic=editImage.getZpic();
                String fpic=editImage.getFpic();
                eimageList.add(zpic);
                eimageList.add(fpic);
            }
            orderInfo.setEimageList(eimageList);
            orderInfoList.add(orderInfo);
        }
        orderDescMa.setOrderInfos(orderInfoList);
        List<WuliuDesc> wuliuDescs=managerMapper.getWuliuList(order.getTrackingNo());
        orderDescMa.setWuliuDescs(wuliuDescs);
        return orderDescMa;
    }


    /**
     * 自动报单
     * 查看订单冷静表中有没有超过4小时的订单
     * 有 自动添加pdf文件 并且修改订单表，然后把此记录从冷静表移出
     * */
    @Override
    public void refreshWaitOrder() {
        long caozuotime=System.currentTimeMillis();
        managerMapper.updateWaitOrderStatus(caozuotime);
        List<WaitOrder> list=managerMapper.getWaitOrders(caozuotime);
        for (WaitOrder waitOrder : list) {
            String orderId = waitOrder.getOrderId();
            int type = waitOrder.getType();
            if (type == 2){
                //用订单去获取子订单
                List<Integer> oidList=managerMapper.getAllOidByOrderId(orderId);
                int totalNum=0;
                int totalYeshu=0;
                String totalSize="";
                for (Integer oid : oidList) {
                    totalNum=totalNum+1;
                    List<String> result = new ArrayList<>();
                    int two=managerMapper.getGoodsIsTwo(oid);
                    //先添加封面正反
                    //1.获取订单二维码图片
                    String qrcode=qrCodeGenerator.generateQRCode(orderId);
                    String temp_z=managerMapper.getPdfCoverTemp(8,oid);
                    String temp_f=managerMapper.getPdfCoverTemp(9,oid);

                    List<EditImage> editImages = managerMapper.getEditImageByOid(oid);
                    //获取编辑图第一张
                    //获取编辑图最后一张
                    String pdfFirstPic=editImages.get(0).getZpic();
                    String pdfLastPic=editImages.get(editImages.size()-1).getFpic();
                    if (two==1){
                        pdfLastPic=editImages.get(editImages.size()-1).getZpic();
                    }
                    String pdfcover=pdfCover.getCover(orderId,oid,temp_z,qrcode,pdfFirstPic,pdfLastPic);
                    result.add(pdfcover);
                    if (two==2) {
                        result.add(temp_f);
                    }

                    int yeshu = 1;
                    if (two==2){
                        yeshu = 2;
                    }
                    for (EditImage editImage : editImages) {
                        String zpic = editImage.getZpic();
                        String fpic = editImage.getFpic();
                        int num = editImage.getNum();
                        yeshu = yeshu + num*2;
                        for (int i = 0; i < num; i++) {
                            result.add(zpic);
                            if (two==2){
                                result.add(fpic);
                            }
                        }
                    }
                    totalYeshu=totalYeshu+yeshu;
                    Convert2Pdf convert2Pdf = new Convert2Pdf();
                    String imageDirPath = "./upload/pdfs/";
                    File imageDir = new File(imageDirPath);
                    if (!imageDir.exists()) {
                        imageDir.mkdirs();
                    }
                    String pdfPath = imageDirPath + orderId +"_"+oid + ".pdf";
                    if (!result.isEmpty()) {
                        String pdfSize = convert2Pdf.convert(result, pdfPath);
                        totalSize=pdfSize;
//                        String urlPrefix = "http://192.168.0.108:8883/";
                        String urlPrefix = "https://yskj.wscapp.com/mwk/";
                        String pdfUrl = urlPrefix + "upload/pdfs/" + orderId +"_"+oid + ".pdf";
                        managerMapper.addPdfLogs(oid,orderId,pdfUrl);
                    }
                }
                String createTime = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
                int res=managerMapper.updateOrdersBaodan(createTime, totalNum, totalSize , totalYeshu, "", orderId);
                if (res>=1){
                    managerMapper.delWaitOrder(orderId,type);
                }
            }else if(type == 1){
                List<String> orderIds = managerMapper.getAllOrderIdBySystemId(orderId);
                for (String id : orderIds) {
                    List<Integer> oidList=managerMapper.getAllOidByOrderId(id);
                    int totalNum=0;
                    int totalYeshu=0;
                    String totalSize="";
                    for (Integer oid : oidList) {
                        totalNum=totalNum+1;
                        List<String> result = new ArrayList<>();
                        List<EditImage> editImages = managerMapper.getEditImageByOid(oid);
                        int two=managerMapper.getGoodsIsTwo(oid);
                        String qrcode=qrCodeGenerator.generateQRCode(id);
                        String temp_z=managerMapper.getPdfCoverTemp(8,oid);
                        String temp_f=managerMapper.getPdfCoverTemp(9,oid);
                        //获取编辑图第一张
                        //获取编辑图最后一张
                        String pdfFirstPic=editImages.get(0).getZpic();
                        String pdfLastPic=editImages.get(editImages.size()-1).getFpic();
                        if (two==1){
                            pdfLastPic=editImages.get(editImages.size()-1).getZpic();
                        }

                        String pdfcover=pdfCover.getCover(id,oid,temp_z,qrcode,pdfFirstPic,pdfLastPic);
                        result.add(pdfcover);
                        if (two==2) {
                            result.add(temp_f);
                        }

                        int yeshu = 1;
                        if (two==2){
                            yeshu = 2;
                        }
                        for (EditImage editImage : editImages) {
                            String zpic = editImage.getZpic();
                            String fpic = editImage.getFpic();
                            int num = editImage.getNum();
                            yeshu = yeshu + num*2;
                            for (int i = 0; i < num; i++) {
                                result.add(zpic);
                                if (two==2){
                                    result.add(fpic);
                                }
                            }
                        }
                        totalYeshu=totalYeshu+yeshu;
                        Convert2Pdf convert2Pdf = new Convert2Pdf();

                        String imageDirPath = "./upload/pdfs/";
                        File imageDir = new File(imageDirPath);
                        if (!imageDir.exists()) {
                            imageDir.mkdirs();
                        }
                        String pdfPath = imageDirPath + id+"_"+oid + ".pdf";
                        if (!result.isEmpty()) {
                            String pdfSize = convert2Pdf.convert(result, pdfPath);
                            totalSize=pdfSize;
//                            String urlPrefix = "http://192.168.0.108:8883/";
                            String urlPrefix = "https://yskj.wscapp.com/mwk/";
                            String pdfUrl = urlPrefix + "upload/pdfs/" + id+"_"+oid + ".pdf";
                            managerMapper.addPdfLogs(oid,id,pdfUrl);
                        }
                    }
                    String createTime = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
                    int res=managerMapper.updateOrdersBaodan(createTime, totalNum, totalSize , totalYeshu, "", id);

                    if (res>=1){
                        managerMapper.delWaitOrder(orderId,type);
                    }
                }
            }
        }
    }


    /**
     * 批量下载pdf
     *
     * */
    @Override
    public List<String> batchDownloadPdf(String orderIds) {
        List<String> result = new ArrayList<>();
        String[] ids = orderIds.split(";");
        // 2. 遍历数组
        for (String orderId : ids) {
            List<String> list=managerMapper.getPdfByOrderId(orderId);
            for (String pdfUrl : list) {
                if (pdfUrl != null && !pdfUrl.isEmpty()) {
                    result.add(pdfUrl);
                    String createTime = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
                    managerMapper.updateOrdersDownloadStatus(createTime,orderId);
                }
            }
        }
        return result;
    }

    @Override
    public List<Integer> getIndexManagerData(int accountType, int accountId) {
        List<Integer> list = new ArrayList<>();
        int num1=managerMapper.getAllUnshippedOrdersNum(accountType,accountId);
        String yesterday = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -1), "yyyy-MM-dd");
        int num2=managerMapper.getYesterdaySendOrdersNum(accountType,accountId,yesterday);
        list.add(num1);
        list.add(num2);
        return list;
    }
}
